using System;
using HubbleTelescope.Model;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace HubbleTelescopeIPhone
{
	/// <summary>
	/// Controller that coordinates with the Telescope Model class
	/// </summary>
	public partial class TelescopeController : UITableViewController
	{
		//A few member variables
		private Telescope _telescope = null;
		private DataSource _dataSource = null;
		
		#region Data Source
		
		/// <summary>
		/// Data source for the UITableViewController
		/// </summary>
		private class DataSource : UITableViewSource
		{
			//ID for re-using UITableViewCells
			private const string _id = "TelescopeCell";
			
			public Planet[] Planets
			{
				get;
				set;
			}
			
			#region implemented abstract members of MonoTouch.UIKit.UITableViewSource
			
			//Returns number of items in list
			public override int RowsInSection (UITableView tableview, int section)
			{
				return Planets == null ? 0 : Planets.Length;
			}
			
			//Returns the actual UITableViewCell
			public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
			{
				var cell = tableView.DequeueReusableCell(_id);
				var planet = Planets[indexPath.Row];
				if (cell == null)
				{
					cell = new UITableViewCell(UITableViewCellStyle.Value1, _id);
				}
				cell.TextLabel.Text = planet.Name;
				cell.DetailTextLabel.Text = string.Format("{0} KM", planet.Diameter);		
				return cell;
			}
			
			#endregion			
		}
		
		#endregion
		
		#region Constructors
	
		public TelescopeController (IntPtr handle) : base (handle)
		{
			Initialize();
		}
	
		[Export("initWithCoder:")]
		public TelescopeController (NSCoder coder) : base(coder)
		{
			Initialize();
		}
	
		protected virtual void Initialize()
		{
			_telescope = new Telescope();
			_dataSource = new DataSource();
		}
	
		#endregion
		
		public override void ViewDidLoad()
		{
			base.ViewDidLoad();
			
			//Set our data source
			TableView.Source = _dataSource;
			
			//Hook up our telescope event
			_telescope.PlanetsMeasured += (sender, e) =>
			{
				_dataSource.Planets = e.Planets;
				
				BeginInvokeOnMainThread(() =>
				{
					View.UserInteractionEnabled = 
						_indicator.Hidden = true;
					TableView.ReloadData();	
				});
			};
		}
		
		/// <summary>
		/// Action to refresh the list of Planets
		/// </summary>
		/// <param name="item">
		/// A <see cref="UIBarButtonItem"/>
		/// </param>
		partial void Refresh(UIBarButtonItem item)
		{
			//Set our progress indicator and disable the view
			View.UserInteractionEnabled = 
				_indicator.Hidden = false;
			
			//Clear out our list, just for aesthetics
			_dataSource.Planets = null;
			TableView.ReloadData();
			
			//Measure the planets
			_telescope.MeasurePlanets();
		}
	}
}

